package com.wjerp.tplus.server.domain.service.impl;

import com.wjerp.tplus.server.api.request.AddReimburseMemberInfoRequest;
import com.wjerp.tplus.server.api.request.QueryReimburseMemberListRequest;
import com.wjerp.tplus.server.api.response.PageDataResponse;
import com.wjerp.tplus.server.api.response.ReimburseMemberInfoResponse;
import com.wjerp.tplus.server.common.constant.DataStatus;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.exception.ServiceException;
import com.wjerp.tplus.server.common.utils.ExcelComponent;
import com.wjerp.tplus.server.domain.entity.invoice.mng.ReimburseMemberInfo;
import com.wjerp.tplus.server.domain.entity.sys.UserInfo;
import com.wjerp.tplus.server.domain.mapper.ReimburseMemberInfoMapper;
import com.wjerp.tplus.server.domain.mapper.UserInfoMapper;
import com.wjerp.tplus.server.domain.service.ReimburseMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lishuailei
 */
@Service
public class ReimburseMemberServiceImpl implements ReimburseMemberService {

    @Resource
    private ReimburseMemberInfoMapper reimburseMemberInfoMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private ExcelComponent excelComponent;

    @Override
    public PageDataResponse<ReimburseMemberInfoResponse> loadReimburseMember(QueryReimburseMemberListRequest request) {
        //获取报销人员信息
        List<ReimburseMemberInfo> reimburseMemberInfoList = reimburseMemberInfoMapper.loadReimburseMember(request);
        Integer totalCount = 0;
        List<ReimburseMemberInfoResponse> reimburseMemberInfoResponses = new ArrayList<>();
        if(!CollectionUtils.isEmpty(reimburseMemberInfoList)){
            //获取记录数
            totalCount = reimburseMemberInfoMapper.loadReimburseMemberCount(request);
            List<String> displayUserIdList = reimburseMemberInfoList.stream().map(ReimburseMemberInfo::getCreatedUser).distinct().collect(Collectors.toList());
            displayUserIdList.addAll(reimburseMemberInfoList.stream().map(ReimburseMemberInfo::getUpdatedUser).distinct().collect(Collectors.toList()));
            List<UserInfo> userInfos = userInfoMapper.selectByDisplayUserIds(displayUserIdList);
            Map<String, List<UserInfo>> userInfoMap = userInfos.stream().collect(Collectors.groupingBy(UserInfo::getDisplayUserId));
            reimburseMemberInfoList.stream().forEach(data->{
                ReimburseMemberInfoResponse reimburseMemberInfoResponse = new ReimburseMemberInfoResponse();
                BeanUtils.copyProperties(data,reimburseMemberInfoResponse);
                reimburseMemberInfoResponse.setCreatedUsername(userInfoMap.get(data.getCreatedUser()).get(0).getName());
                reimburseMemberInfoResponse.setUpdatedUsername(userInfoMap.get(data.getUpdatedUser()).get(0).getName());
                reimburseMemberInfoResponses.add(reimburseMemberInfoResponse);
            });
        }

        return new PageDataResponse<>(totalCount,reimburseMemberInfoResponses);
    }

    @Override
    public void addReimburseMember(AddReimburseMemberInfoRequest request, String currentLoginDisplayUserId, String companyCode) throws BusinessException {
        //1.校验报销人员编码是否存在
        checkReimburseMemberCode(companyCode,request.getReimburseCode());
        //2.新增报销人员
        ReimburseMemberInfo reimburseMemberInfo = new ReimburseMemberInfo();
        reimburseMemberInfo.setCompanyCode(companyCode);
        reimburseMemberInfo.setName(request.getName());
        reimburseMemberInfo.setMemberCode(request.getReimburseCode());
        reimburseMemberInfo.setIsDeleted(0);
        reimburseMemberInfo.setCreatedTime(new Date());
        reimburseMemberInfo.setUpdatedTime(new Date());
        reimburseMemberInfo.setCreatedUser(currentLoginDisplayUserId);
        reimburseMemberInfo.setUpdatedUser(currentLoginDisplayUserId);

        int result = reimburseMemberInfoMapper.insertSelective(reimburseMemberInfo);
        if( result <= 0){
            throw new BusinessException("新增报销人员信息失败，请重试");
        }
    }

    @Override
    public void updateReimburseMemberStatus(String reimburseMemberCode, String currentLoginDisplayUserId, String companyCode, DataStatus dataStatus) throws BusinessException {
        //获取报销人员
        ReimburseMemberInfo reimburseMemberInfo = reimburseMemberInfoMapper.selectByMemberCodeAndCompanyCode(reimburseMemberCode,companyCode);
        if(reimburseMemberInfo == null){
            throw new BusinessException("操作失败，报销人员不存在");
        }
        //更新状态信息
        reimburseMemberInfo.setUpdatedUser(currentLoginDisplayUserId);
        reimburseMemberInfo.setUpdatedTime(new Date());
        if(dataStatus == DataStatus.DELETE){
            reimburseMemberInfo.setIsDeleted(1);
        }else{
            reimburseMemberInfo.setIsDeleted(0);
        }
        int result = reimburseMemberInfoMapper.updateByPrimaryKeySelective(reimburseMemberInfo);
        if(result <= 0){
            throw new BusinessException("操作失败，更新异常，请重试");
        }
    }

    @Override
    public List<ReimburseMemberInfo> loadReimburseMemberByReimburseMemberCodeList(List<String> reimburseMemberCodeList) {
        if(CollectionUtils.isEmpty(reimburseMemberCodeList)){
            return Collections.emptyList();
        }
        return reimburseMemberInfoMapper.selectByMemberCodeList(reimburseMemberCodeList);
    }

    @Override
    public void updateReimburseMember(AddReimburseMemberInfoRequest request, String displayUserId, String companyCode) throws BusinessException {
        //获取报销人员
        ReimburseMemberInfo reimburseMemberInfo = reimburseMemberInfoMapper.selectByMemberCodeAndCompanyCode(request.getReimburseCode(),companyCode);
        if(reimburseMemberInfo == null){
            throw new BusinessException("操作失败，报销人员不存在");
        }

        reimburseMemberInfo.setUpdatedUser(displayUserId);
        reimburseMemberInfo.setUpdatedTime(new Date());
        reimburseMemberInfo.setMemberCode(request.getReimburseCode());
        reimburseMemberInfo.setName(request.getName());

        int result = reimburseMemberInfoMapper.updateByPrimaryKeySelective(reimburseMemberInfo);
        if(result <= 0){
            throw new BusinessException("操作失败，更新异常，请重试");
        }
    }

    @Override
    public List<ReimburseMemberInfo> loadAllReimburseMember() {
        return reimburseMemberInfoMapper.selectByIsDeleted(0);
    }

    @Override
    public void importReimburseByFile(MultipartFile file, String companyCode, String displayUserId) throws ServiceException, BusinessException {
        List<AddReimburseMemberInfoRequest> reimburseMemberInfoList = excelComponent.getReimburseInfoByFile(file);
        if(CollectionUtils.isEmpty(reimburseMemberInfoList)){
            throw new ServiceException("文件内容不能为空");
        }

        for (AddReimburseMemberInfoRequest request : reimburseMemberInfoList) {
            addReimburseMember(request, displayUserId,companyCode);
        }

    }


    /**
     * 校验报销人员编码是否存在
     * @param companyCode
     * @param reimburseCode 报销人员编码
     */
    private void checkReimburseMemberCode(String companyCode, String reimburseCode) throws BusinessException {
        if(StringUtils.isEmpty(reimburseCode)){
            throw new BusinessException("报销人员编码不能为空");
        }

        //1.根据报销人员编码获取报销人员信息
        ReimburseMemberInfo reimburseMemberInfo =  reimburseMemberInfoMapper.selectByMemberCodeAndCompanyCode(reimburseCode,companyCode);
        if(reimburseMemberInfo != null){
            throw new BusinessException("报销人员编码已经存在，请重新输入");
        }
    }
}
